package com.mes.handler.plan;

import com.mes.manufacture.data.EmesoManuOrder;
import com.mes.plan.data.EmespPlanOrder;
import org.apache.log4j.Logger;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.openbravo.base.exception.OBException;
import org.openbravo.client.kernel.BaseActionHandler;
import org.openbravo.dal.service.OBDal;
import org.openbravo.database.SessionInfo;
import org.openbravo.model.ad.access.User;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 计划订单审核
 * @author ZT
 */
public class PlanOrderAuditHandler extends BaseActionHandler {
	private Logger logger = Logger.getLogger(this.getClass());
	
	@Override
	protected JSONObject execute(Map<String, Object> parameters, String data) {
		JSONObject jsonRep = new JSONObject();
		try {
			JSONObject jsonData = new JSONObject(data);
			String id = jsonData.getString("recordId");
			
			EmespPlanOrder order = OBDal.getInstance().get(EmespPlanOrder.class, id);
			List<EmesoManuOrder> list = null;
			
			if ("WAIT".equals(order.getStatus())) {
				order.setStatus("RELEASE");
				order.setCheckDate(new Date());
				User user = OBDal.getInstance().get(User.class, SessionInfo.getUserId());
				order.setCheckUser(user);
				//更改所有生产订单状态
				list =  order.getEmesoManuOrderList();
				for (EmesoManuOrder o : list){
					o.setAudit(true);
					OBDal.getInstance().save(o);
				};
				OBDal.getInstance().save(order);
				
				jsonRep.put("result", true);
				jsonRep.put("msg", "审核成功！");
				OBDal.getInstance().commitAndClose();
			} else {
				jsonRep.put("result", false);
				jsonRep.put("msg", "当前计划已审核！");
				OBDal.getInstance().rollbackAndClose();
			}
			
		} catch (Exception e) {
			OBDal.getInstance().rollbackAndClose();
			logger.error("计划订单审核失败：", e);
			try {
				jsonRep.put("result", false);
				jsonRep.put("msg", "审核失败！");
			} catch (JSONException e1) {
			}
			throw new OBException(e);
		}
		return jsonRep;
	}
}